import 'package:cached_network_image/cached_network_image.dart';
import 'package:cher_flare/common/models/ly_broadcaster_model.dart';
import 'package:cher_flare/common/models/ly_user_works_model.dart';
import 'package:cher_flare/utils/app_color.dart';
import 'package:cher_flare/utils/ly_data_manager.dart';
import 'package:cher_flare/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../common/widgets/ly_action_sheet_page.dart';
import '../../config/url_api.dart';
import '../../http/http_utils.dart';
import '../../routes/app_pages.dart';
import '../discovery/ly_discovery_card_item.dart';

class LYUserPage extends StatefulWidget {
  const LYUserPage({super.key});

  @override
  State<LYUserPage> createState() => _LYUserPageState();
}

class _LYUserPageState extends State<LYUserPage> {
  String? userId;
  String? nickname;
  String? avatar;
  int selectedIndex = 0;
  LyBroadcasterModel? userModel;

  List<LYWorksModel>? worksList;
  @override
  void initState() {
    super.initState();
    userId = Get.arguments['userId'];
    nickname = Get.arguments['nickname'];
    avatar = Get.arguments['avatar'];

    if (LYDataManager.share.allUserWorks.isEmpty) {
      LYDataManager.share.initUserAndWorksData().then((value) {
        _searchUserWorks();
      });
    } else {
      _searchUserWorks();
    }
    if (userId != null) {
      LYDataManager.share.searchUser(userId!).then((value) {
        userModel = value;
        setState(() {});
      });
    }
  }

  void _searchUserWorks() {
    worksList = LYDataManager.share.allUserWorks.where((element) {
      return element.userId == userId;
    }).toList();
    setState(() {});
  }

  void _itemDidClick(int index) {
    if (selectedIndex == index) {
      return;
    }
    selectedIndex = index;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Utils.commonAppBar(),
      backgroundColor: AppColors.whiteColor,
      body: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
            top: 24,
            child: SizedBox(
              height: 132,
              child: Stack(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(62),
                    child: CachedNetworkImage(
                      imageUrl: avatar ?? '',
                      width: 124,
                      height: 124,
                      fit: BoxFit.cover,
                    ),
                  ),
                  Positioned(
                      top: 100,
                      left: 84,
                      child: InkWell(
                        onTap: () => _followDidClick(),
                        child: Image.asset(
                          'assets/images/user_page_love_${userModel?.isFriend == true ? "h" : "n"}.png',
                          width: 32,
                          height: 32,
                        ),
                      )),
                ],
              ),
            ),
          ),
          Positioned(
              top: 160,
              left: 20,
              right: 20,
              child: Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.only(top: 12),
                  child: Text(
                    nickname ?? '',
                    style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: AppColors.color404040),
                  ))),
          Positioned(
              top: 256,
              left: 0,
              right: 0,
              bottom: 0,
              child: Container(
                decoration: const BoxDecoration(
                    color: AppColors.colorEEFDEF,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(30),
                        topRight: Radius.circular(30))),
                child: IndexedStack(
                  sizing: StackFit.expand,
                  index: selectedIndex,
                  children: [
                    Positioned(
                        top: 53,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        child: ListView.separated(
                          padding: const EdgeInsets.all(16),
                          itemBuilder: (ctx, index) {
                            final model = worksList![index];
                            return LYDiscoveryCardItem(
                              image: model.cover,
                              title: model.title,
                              content: model.description,
                              avatar: model.avatar,
                              nickName: model.nickname,
                              isGreat: model.isGreat ?? false,
                              isSave: model.isSave,
                              onTap: () {
                                _worksDidClick(model);
                              },
                              greatOnTap: () => _greatDidClick(model),
                            );
                          },
                          separatorBuilder: (ctx, index) {
                            return const SizedBox(
                              height: 16,
                            );
                          },
                          itemCount: worksList?.length ?? 0,
                          cacheExtent: 320,
                        )),
                    Positioned(
                        top: 63,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        child: Container(
                          alignment: Alignment.topCenter,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              _makeItem('medal_seed_0.png'),
                              _makeItem('medal_sapling_0.png'),
                              _makeItem('medal_bloom_0.png'),
                              _makeItem('medal_gains_0.png')
                            ],
                          ),
                        )),
                  ],
                ),
              )),
          Positioned(
              top: 227,
              height: 58,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  InkWell(
                    onTap: () => _itemDidClick(0),
                    child: Image.asset(
                      'assets/images/user_page_works_${selectedIndex == 0 ? 'h' : 'n'}.png',
                      width: 58,
                      height: 58,
                    ),
                  ),
                  const SizedBox(
                    width: 74,
                  ),
                  InkWell(
                    onTap: () => _itemDidClick(1),
                    child: Image.asset(
                      'assets/images/user_page_medal_${selectedIndex == 1 ? "h" : 'n'}.png',
                      width: 58,
                      height: 58,
                    ),
                  )
                ],
              )),
        ],
      ),
    );
  }

  Widget _makeItem(String imgName) {
    return Container(
      width: 63,
      height: 63,
      alignment: Alignment.center,
      child: Image.asset(
        'assets/images/$imgName',
      ),
    );
  }

  void _worksDidClick(LYWorksModel model) {
    Get.toNamed(AppPages.worksDetailPage, arguments: {'works': model});
  }

  void _greatDidClick(LYWorksModel model) {
    model.isGreat = !(model.isGreat ?? false);
    LYDataManager.share.updateLocalWorksData();
    setState(() {});
  }

  void _followDidClick() async {
    EasyLoading.show();
    if (userModel?.isFriend == true) {
      final response = await HttpUtils.getInstance
          .post(URLApi.unfriend, data: {'followUserId': userId});
      userModel?.isFriend = !(userModel?.isFriend ?? false);
    } else {
      final response = await HttpUtils.getInstance
          .post(URLApi.addFriend, data: {'followUserId': userId});
      userModel?.isFriend = !(userModel?.isFriend ?? false);
    }
    LYDataManager.share.updateLocalWorksData();
    setState(() {});
    EasyLoading.dismiss();
  }
}
